package com.wujunshen.algorithm.leetcode.basic;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2022/6/30 18:04<br>
 */
@Slf4j
public class 两数之和 {
  // 提示：
  // 2 <= nums.length <= 104
  // -109 <= nums[i] <= 109
  // -109 <= target <= 109
  // 只会存在一个有效答案
  public static int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();

    if (nums.length < 2 || nums.length > Math.pow(10, 4)) {
      throw new IllegalArgumentException("exception");
    }

    if (target < Math.pow(-10, 9) || target > Math.pow(10, 9)) {
      throw new IllegalArgumentException("exception");
    }

    for (int i = 0; i < nums.length; i++) {
      if (nums[i] < Math.pow(-10, 9) || target > Math.pow(10, 9)) {
        throw new IllegalArgumentException("exception");
      }

      if (map.containsKey(target - nums[i])) {
        return new int[] {map.get(target - nums[i]), i};
      }
      map.put(nums[i], i);
    }
    throw new IllegalArgumentException("exception");
  }

  public static void main(String[] args) {
    int[] nums = new int[] {2, 7, 11, 15};
    int target = 9;

    int[] result = twoSum(nums, target);
    // [0,1]
    log.info("答案: {}", result);

    nums = new int[] {3, 2, 4};
    target = 6;

    result = twoSum(nums, target);
    // [1,2]
    log.info("答案: {}", result);

    nums = new int[] {3, 3};
    target = 6;

    result = twoSum(nums, target);
    // [0,1]
    log.info("答案: {}", result);

    nums = new int[] {3, 3, 3, 3};
    target = 6;

    result = twoSum(nums, target);
    // [0,1]
    log.info("答案: {}", result);
  }
}
